package com.hqbzl.chat.handler;

import com.hqbzl.chat.factory.Factory;
import com.hqbzl.chat.model.LoginRequestMessage;
import com.hqbzl.chat.model.LoginResponseMessage;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@Sharable
public final class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
		final String userName = msg.getUserName();
		final String password = msg.getPassword();
		final boolean login = Factory.userService.login(userName, password);
		LoginResponseMessage response;
		if (login) {
			response = LoginResponseMessage.builder().result(true).msg("success").build();
			Factory.session.bind(ctx.channel(), userName);
		} else {
			response = LoginResponseMessage.builder().result(false).msg("fail").build();
		}
		ctx.writeAndFlush(response);
	}
}